package init

import (
	"api-getaway/basic/config"
	"api-getaway/model"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"sync"
	"time"
)

func init() {
	InitMysql()
}

var once sync.Once

func InitMysql() {
	once.Do(func() {
		var err error
		// refer https://github.com/go-sql-driver/mysql#dsn-data-source-name for details
		dsn := "root:123456@tcp(127.0.0.1:3306)/2302a?charset=utf8mb4&parseTime=True&loc=Local"
		config.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
		if err != nil {
			panic("数据库连接失败")
		} else {
			fmt.Println("数据库连接成功")
		}

		sqlDB, err := config.DB.DB()

		// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
		sqlDB.SetMaxIdleConns(10)

		// SetMaxOpenConns sets the maximum number of open connections to the database.
		sqlDB.SetMaxOpenConns(100)

		// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
		sqlDB.SetConnMaxLifetime(time.Hour)

		config.DB.AutoMigrate(&model.Shop{}, &model.DisplayWindow{}, &model.ShowcaseProducts{}, &model.UserOrder{})
	})
}
